import React, { Component, ErrorInfo, ReactNode } from "react";

interface Props {
  children: ReactNode;
  fallback?: ReactNode;
}

interface State {
  hasError: boolean;
  error: Error | null;
}

export class ErrorBoundary extends Component<Props, State> {
  public state: State = {
    hasError: false,
    error: null,
  };

  public static getDerivedStateFromError(error: Error): State {
    return { hasError: true, error };
  }

  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error("ErrorBoundary caught an error:", error, errorInfo);
  }

  public render() {
    if (this.state.hasError) {
      return (
        this.props.fallback || (
          <div
            style={{
              padding: "20px",
              background: "#0f172a",
              color: "#ef4444",
              borderRadius: "8px",
              margin: "10px",
            }}
          >
            <h3>图表加载错误</h3>
            <p style={{ fontSize: "12px", color: "#9ca3af" }}>
              {this.state.error?.message || "未知错误"}
            </p>
            <button
              onClick={() => this.setState({ hasError: false, error: null })}
              style={{
                marginTop: "10px",
                padding: "8px 16px",
                background: "#22c55e",
                color: "#020617",
                border: "none",
                borderRadius: "4px",
                cursor: "pointer",
              }}
            >
              重试
            </button>
          </div>
        )
      );
    }

    return this.props.children;
  }
}


